package com.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
 * @author 徐洲
 * @version 1.0
 */
public class JDBCUtilsByDruid {
    private static DataSource dataSource;

    // 不能是静态代码块，会出错

    //在静态代码块完成 ds 初始化
//    static {
//
//    }

    public JDBCUtilsByDruid(){
        Properties properties = new Properties();
        try{
//            ClassLoader classLoader = JDBCUtilsByDruid.class.getClassLoader();
//            URL resource = classLoader.getResource("config.properties");
//            String path = resource.getFile();
//            System.out.println(path);

            properties.load(new FileInputStream("D:\\Learn\\javaweb\\src\\com\\config.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    //编写 getConnection 方法
    public Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    //关闭连接, 老师再次强调： 在数据库连接池技术中，close 不是真的断掉连接
    //而是把使用的 Connection 对象放回连接池
    public void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}  
